let express = require("express");
let uunewid = require("uuid");
let router = express.Router();

const { ohana } = require("ohana-node-orm");
const tableName = "SAP_JIANGDU_POLICY_CONDITION";
const ohana_instance = new ohana(tableName);
const valueTableName = "SAP_JIANGDU_POLICY_CONDITION_VALUE";
const ohana_instance_value = new ohana(valueTableName);

const { checkAuth } = require("../utils/utils");
let constants = require("../utils/constants");

router.get("/", function (req, res, next) {
    // #swagger.tags = ['政策条件']
    // #swagger.summary = '获取列表'
    // #swagger.description = '需要JWT Token'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    // const user = checkAuth(req.user, constants.BASICAUTH);

    // if (!user.authCheck) {
    //     res.sendStatus(403);
    // }

    getData()
        .then((result) => {
            res.send(result);
        })
        .catch((err) => {
            console.log(err);
        });
});

router.post("/", function (req, res, next) {
    // #swagger.tags = ['政策条件']
    // #swagger.summary = '插入列表'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    /*  #swagger.requestBody = {
                  required: true,
                  content: {
                      "application/json": {
                          schema: {
                              $ref: "#/definitions/policyCondition_add"
                          }  
                      },
                  }
          } */
    let { data } = req.body;
    insertData(data)
        .then((result) => {
            if (result == 1) {
                res.sendStatus(200);
            } else {
                res.sendStatus(500);
            }
        })
        .catch((err) => {
            console.log(err);
        });
});

router.put("/", function (req, res, next) {
    // #swagger.tags = ['政策条件']
    // #swagger.summary = '更新列表'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    /*  #swagger.requestBody = {
                  required: true,
                  content: {
                      "application/json": {
                          schema: {
                              $ref: "#/definitions/policyCondition_update"
                          }  
                      },
                  }
          } */
    const { data } = req.body;
    updateData(data)
        .then((result) => {
            if (result == 1) {
                res.sendStatus(200);
            } else {
                res.sendStatus(500);
            }
        })
        .catch((err) => {
            console.log(err);
        });
});

router.delete("/", function (req, res, next) {
    // #swagger.tags = ['政策条件']
    // #swagger.summary = '删除列表'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    /*  #swagger.requestBody = {
                  required: true,
                  content: {
                      "application/json": {
                          schema: {
                              $ref: "#/definitions/policyCondition_delete"
                          }  
                      },
                  }
          } */
    const { data } = req.body;
    deleteData(data)
        .then((result) => {
            if (result == 1) {
                res.sendStatus(200);
            } else {
                res.sendStatus(500);
            }
        })
        .catch((err) => {
            console.log(err);
        });
});

async function getData(condition) {
    let result = [];
    result = await ohana_instance.find(condition);
    return result;
}

async function insertData(data) {
    data.POLICY_CONDITION_ID = uunewid.v4();
    let result = await ohana_instance.insert(data);
    return result;
}

async function updateData(data) {
    let result = await ohana_instance.update(
        {
            POLICY_CONDITION_ID: data.POLICY_CONDITION_ID,
        },
        data
    );
    return result;
}

async function deleteData(data) {
    let result = ohana_instance.raw(
        "DELETE from " +
        tableName +
        " WHERE POLICY_CONDITION_ID = '" +
        data.POLICY_CONDITION_ID +
        "'"
    );
    return result;
}

router.get("/value", function (req, res, next) {
    // #swagger.tags = ['政策条件']
    // #swagger.summary = '获取value列表'
    // #swagger.description = '需要JWT Token'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    // const user = checkAuth(req.user, constants.BASICAUTH);

    // if (!user.authCheck) {
    //     res.sendStatus(403);
    // }
    let { POLICY_ID } = req.query;
    let condition = {};
    condition.POLICY_ID = POLICY_ID;
    getValueData(condition)
        .then((result) => {
            res.send(result);
        })
        .catch((err) => {
            console.log(err);
        });
});

router.post("/value", function (req, res, next) {
    // #swagger.tags = ['政策条件']
    // #swagger.summary = '插入value列表'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    /*  #swagger.requestBody = {
                  required: true,
                  content: {
                      "application/json": {
                          schema: {
                              $ref: "#/definitions/policyConditionValue_add"
                          }  
                      },
                  }
          } */
    let { data } = req.body;
    insertValueData(data)
        .then((result) => {
            if (result == 1) {
                res.sendStatus(200);
            } else {
                res.sendStatus(500);
            }
        })
        .catch((err) => {
            console.log(err);
        });
});

router.put("/value", function (req, res, next) {
    // #swagger.tags = ['政策条件']
    // #swagger.summary = '更新value列表'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    /*  #swagger.requestBody = {
                  required: true,
                  content: {
                      "application/json": {
                          schema: {
                              $ref: "#/definitions/policyConditionValue_update"
                          }  
                      },
                  }
          } */
    const { data } = req.body;
    updateValueData(data)
        .then((result) => {
            if (result == 1) {
                res.sendStatus(200);
            } else {
                res.sendStatus(500);
            }
        })
        .catch((err) => {
            console.log(err);
        });
});

router.delete("/value", function (req, res, next) {
    // #swagger.tags = ['政策条件']
    // #swagger.summary = '删除value列表'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    /*  #swagger.requestBody = {
                  required: true,
                  content: {
                      "application/json": {
                          schema: {
                              $ref: "#/definitions/policyConditionValue_delete"
                          }  
                      },
                  }
          } */
    const { data } = req.body;
    deleteValueData(data)
        .then((result) => {
            if (result == 1) {
                res.sendStatus(200);
            } else {
                res.sendStatus(500);
            }
        })
        .catch((err) => {
            console.log(err);
        });
});

async function getValueData(condition) {
    let result = await ohana_instance_value.raw(
        "select * from SAP_JIANGDU_POLICY_CONDITION_VALUE as value left join SAP_JIANGDU_POLICY_CONDITION as con on con.policy_condition_id = value.policy_condition_id where value.POLICY_ID = '" +
        condition.POLICY_ID +
        "'"
    );
    return result;
}

async function insertValueData(data) {
    data.POLICY_CONDITION_VALUE = uunewid.v4();
    let result = await ohana_instance_value.insert(data);
    return result;
}

async function updateValueData(data) {
    let result = await ohana_instance_value.update(
        {
            POLICY_CONDITION_VALUE: data.POLICY_CONDITION_VALUE,
        },
        data
    );
    return result;
}

async function deleteValueData(data) {
    let result = ohana_instance_value.raw(
        "DELETE from " +
        valueTableName +
        " WHERE POLICY_CONDITION_VALUE = '" +
        data.POLICY_CONDITION_VALUE +
        "'"
    );
    return result;
}

router.get("/companyForPolicy", function (req, res, next) {
    // #swagger.tags = ['政策条件']
    // #swagger.summary = '测试：获取符合政策条件的company'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    let { POLICY_ID } = req.query;
    let condition = {};
    condition.POLICY_ID = POLICY_ID;
    getCompanyForPolicy(condition)
        .then((result) => {
            res.send(result);
        })
        .catch((err) => {
            console.log(err);
            res.status(500).send(err);
        });
});

async function getCompanyForPolicy(condition) {
    let sqlString = "select COMPANY_NAME from SAP_JIANGDU_USERS_REGISTERED";
    let conditions = await getValueData(condition);
    if (conditions.length > 0) {
        sqlString += " WHERE ";
        for (let index = 0; index < conditions.length; index++) {
            const element = conditions[index];
            let conditionString =
                element.ATTRIBUTE + element.OPERATOR + "'" + element.VALUE + "'";
            sqlString = sqlString + conditionString;
            if (index < conditions.length - 1) {
                sqlString += " AND ";
            }
        }
        console.log(sqlString);
    }
    let result = await ohana_instance.raw(sqlString);
    return { sqlString, result };
}

module.exports = router;
